package dbmethod

import (
	// "fmt"
	"photoPlugIn/config"
	us "photoPlugIn/utils"
	"strconv"
)

type SourcePhoto struct {
	Id        int    `sqlField:"id" sqlType:"integer PRIMARY KEY autoincrement"`
	FileName  string `sqlField:"filename" sqlType:"NVARCHAR(255)"`
	PhotoName string `sqlField:"photoname" sqlType:"NVARCHAR(255)"`
	MD5       string `sqlField:"MD5" sqlType:"CHAR(32)"`
	UserId    int    `sqlField:"userid" sqlType:"int(32)"`
	GroupId   int    `sqlField:"groupid" sqlType:"int(32)"`
	ParentId  int    `sqlField:"parentid" sqlType:"int(32)"`
	FileUrl   string `sqlField:"fileurl" sqlType:"CHAR(1)"`
	IsDir     bool   `sqlField:"isdir" sqlType:"BOOLEAN"`
	Source    string `sqlField:"source" sqlType:"NVARCHAR(255)"`
}

func PhotoListInsert(pid int64, dname, md5 string) int64 {
	db := config.CONFIG.Conn
	stmt, err := db.Prepare("INSERT INTO sourcephoto(filename, photoname, MD5,parentid,source) values(?,?,?,?,?)")
	us.CheckErr(err)
	res, err := stmt.Exec(dname, dname, md5, pid, config.CONFIG.PHOTODB)
	us.CheckErr(err)
	id, err := res.LastInsertId()
	us.CheckErr(err)
	// fmt.Println(id)
	return id
}

func PhotoListFind(ParentId int64, md5, filename string) *SourcePhoto {
	// fmt.Println("测试查找...")
	db := config.CONFIG.Conn
	selectStr := "parentid=" + strconv.FormatInt(ParentId, 10) + " AND " + "MD5=" + "'" + md5 + "'" + " AND " + "filename=" + "'" + filename + "'" + " limit 0,1"
	// fmt.Println("sqlCmd:", "SELECT id,MD5,filename FROM sourcephoto WHERE "+selectStr)
	rows, err := db.Query("SELECT id,MD5,filename FROM sourcephoto WHERE " + selectStr)
	us.CheckErr(err)
	defer rows.Close()
	p := new(SourcePhoto)
	for rows.Next() {
		err := rows.Scan(&p.Id, &p.MD5, &p.FileName)
		us.CheckErr(err)
		// fmt.Println(p.Id, p.MD5, p.FileName)
	}
	return p
}

func GetPhotoLists(ParentId int64) []SourcePhoto {
	// fmt.Println("测试查找...")
	db := config.CONFIG.Conn
	selectStr := "parentid=" + strconv.FormatInt(ParentId, 10)
	// fmt.Println("sqlCmd:", "SELECT id,MD5,filename,photoname FROM sourcephoto WHERE "+selectStr)
	rows, err := db.Query("SELECT id,MD5,filename,photoname FROM sourcephoto WHERE " + selectStr)
	us.CheckErr(err)
	defer rows.Close()
	p := []SourcePhoto{}
	fori := 0
	for rows.Next() {
		p = append(p, SourcePhoto{})
		err := rows.Scan(&p[fori].Id, &p[fori].MD5, &p[fori].FileName, &p[fori].PhotoName)
		fori++
		us.CheckErr(err)
		// fmt.Println(p.Id, p.MD5, p.FileName)
	}
	return p
}
